
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.swing.JPanel;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.general.SeriesException;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.RefineryUtilities;

/**
 * An example of a time series chart.  For the most part, default settings are
 * used, except that the renderer is modified to show filled shapes (as well as
 * lines) at each data point.
 */
public class TimeSeriesChartDemo1 extends ApplicationFrame {

	private static final long serialVersionUID = 1L;

	{
		ChartFactory.setChartTheme(new StandardChartTheme("JFree/Shadow",true));
	}

	/**
	 * A demonstration application showing how to create a simple time series
	 * chart.  This example uses monthly data.
	 *
	 * @param title  the frame title.
	 */
	public TimeSeriesChartDemo1(String title){
		super(title);
		ChartPanel chartPanel = (ChartPanel) createDemoPanel();

		setContentPane(chartPanel);
		chartPanel.setPreferredSize(new java.awt.Dimension(500, 400));
	}

	/**
	 * Creates a chart.
	 *
	 * @param dataset  a dataset.
	 *
	 * @return A chart.
	 */
	private static JFreeChart createChart(XYDataset dataset) {

		JFreeChart chart = ChartFactory.createTimeSeriesChart(
				"Income vs Expenditure",  // title
				"Date",             // x-axis label
				"Amount",   // y-axis label
				dataset,            // data
				true,               // create legend?
				true,               // generate tooltips?
				false               // generate URLs?
				);

		chart.setBackgroundPaint(Color.white);

		XYPlot plot = (XYPlot) chart.getPlot();
		plot.setBackgroundPaint(Color.lightGray);
		plot.setDomainGridlinePaint(Color.white);
		plot.setRangeGridlinePaint(Color.white);
		plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
		plot.setDomainCrosshairVisible(true);
		plot.setRangeCrosshairVisible(true);
		XYItemRenderer r = plot.getRenderer();
		if (r instanceof XYLineAndShapeRenderer) {
			XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
			renderer.setBaseShapesVisible(true);
			renderer.setBaseShapesFilled(true);
			renderer.setDrawSeriesLineAsPath(true);
		}

		DateAxis axis = (DateAxis) plot.getDomainAxis();
		axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
		//axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));

		return chart;

	}

	/**
	 * Creates a dataset, consisting of two series of monthly data.
	 *
	 * @return The dataset.
	 */
	@SuppressWarnings("unchecked")
	private static XYDataset createDataset(){
		TimeSeries s1 = new TimeSeries("Income");
		TimeSeries s2 = new TimeSeries("Expenditure");
		/*		String dateStart = PlotGraph.tfStartDate.getText();
		String dateEnd = PlotGraph.tfEndDate.getText();*/
		String dateStart = "01-01-2000";
		String dateEnd = "01-01-2015";

		File filename = new File("IncomeList.ser");
		FileInputStream fis = null;
		ObjectInputStream in = null;
		if(filename.exists())
		{
			try {
				fis = new FileInputStream(filename);
				in = new ObjectInputStream(fis);
				Income.incomeList = (ArrayList<Income>) in.readObject();//Reads in the income list from the file
				in.close();
			} catch (Exception ex) {
				System.out.println("Exception during deserialization: " +
						ex); 
				ex.printStackTrace();
			}
		}
		
		File expFile = new File("ExpenditureList.ser");
/*		FileInputStream fis = null;
		ObjectInputStream in = null;*/
		if(expFile.exists())
		{
			try {
				fis = new FileInputStream(expFile);
				in = new ObjectInputStream(fis);
				Expenditure.expenditureList = (ArrayList<Expenditure>) in.readObject();//Reads in the income list from the file
				in.close();
			} catch (Exception ex) {
				System.out.println("Exception during deserialization: " +
						ex); 
				ex.printStackTrace();
			}
		}
		
		// dataset.setValue(incomeAdd.getDescription(),incomeAdd.getAmount());

		Calendar calStartDate = new GregorianCalendar();
		Calendar calEndDate = new GregorianCalendar();



		java.util.Date startDate;
		try {
			startDate = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(dateStart);

			calStartDate.setTime(startDate);
			java.util.Date endDate = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(dateEnd);
			calEndDate.setTime(endDate);

			for(int i = 0; i<Income.incomeList.size();i++)//loops through each patient
			{
				Income incomeGraph = Income.incomeList.get(i);

				String strDateCompare = incomeGraph.getDate().toString();//Gets date from invoice
				Calendar calDateCompare = new GregorianCalendar();
				java.util.Date dtDateCompare = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(strDateCompare);//converts string to date
				calDateCompare.setTime(dtDateCompare);

				if(calDateCompare.after(calStartDate) && calDateCompare.before(calEndDate))
				{


					try
					{
						s1.add(new Month(calDateCompare.get(Calendar.MONTH), calDateCompare.get(Calendar.YEAR)), incomeGraph.getAmount());
					}
					catch(SeriesException e)
					{							
						Double newAmount =(Double) s1.getDataItem(new Month(calDateCompare.get(Calendar.MONTH), calDateCompare.get(Calendar.YEAR))).getValue();
						s1.addOrUpdate(new Month(calDateCompare.get(Calendar.MONTH), calDateCompare.get(Calendar.YEAR)), incomeGraph.getAmount() + newAmount);
					}
					//System.out.println(s1.getDataItem(i).getPeriod().toString());
				}

			}
			
			for(int i = 0; i<Expenditure.expenditureList.size();i++)//loops through each patient
			{
				Expenditure expenseGraph = Expenditure.expenditureList.get(i);

				String strDateCompare = expenseGraph.getDate().toString();//Gets date from invoice
				Calendar calDateCompare = new GregorianCalendar();
				java.util.Date dtDateCompare = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(strDateCompare);//converts string to date
				calDateCompare.setTime(dtDateCompare);

				if(calDateCompare.after(calStartDate) && calDateCompare.before(calEndDate))
				{


					try
					{
						s2.add(new Month(calDateCompare.get(Calendar.MONTH), calDateCompare.get(Calendar.YEAR)), expenseGraph.getAmount());
					}
					catch(SeriesException e)
					{							
						Double newAmount =(Double) s2.getDataItem(new Month(calDateCompare.get(Calendar.MONTH), calDateCompare.get(Calendar.YEAR))).getValue();
						s2.addOrUpdate(new Month(calDateCompare.get(Calendar.MONTH), calDateCompare.get(Calendar.YEAR)), expenseGraph.getAmount() + newAmount);
					}
					//System.out.println(s1.getDataItem(i).getPeriod().toString());
				}

			}

		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		TimeSeriesCollection dataset = new TimeSeriesCollection();
		dataset.addSeries(s1);
		dataset.addSeries(s2);

		return dataset;

	}

	/**
	 * Creates a panel for the demo (used by SuperDemo.java).
	 *
	 * @return A panel.
	 */
	public static JPanel createDemoPanel(){
		JFreeChart chart = createChart(createDataset());
		ChartPanel panel = new ChartPanel(chart);
		panel.setFillZoomRectangle(true);
		panel.setMouseWheelEnabled(true);
		return panel;
	}

	/**
	 * Starting point for the demonstration application.
	 *
	 * @param args  ignored.
	 */
	public static void main(String[] args){

		TimeSeriesChartDemo1 demo = new TimeSeriesChartDemo1(
				"Time Series Chart Demo 1");
		demo.pack();
		RefineryUtilities.centerFrameOnScreen(demo);
		demo.setVisible(true);

	}


}
